package com.marvels.financial.loan.service.impl;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fintech.third.service.shzx.ShzxService;
import com.marvels.approve.common.dao.McamLoanApplyInfoCommonDao;
import com.marvels.common.utils.MarvelsLogUtil;
import com.marvels.common.utils.ServerProperties;
import com.marvels.financial.consum.FinancialConsumerApproveApi;
import com.marvels.financial.consum.FinancialConsumerExternalApi;
import com.marvels.financial.loan.dao.McfeCustomerRepaymentPlanDao;
import com.marvels.financial.loan.dao.ShzxUploadDataDao;
import com.marvels.financial.loan.dto.ExcelInfo;
import com.marvels.financial.loan.dto.IdentityInformation;
import com.marvels.financial.loan.dto.LoanApplicationInformation;
import com.marvels.financial.loan.dto.LoanBusinessInformation;
import com.marvels.financial.loan.dto.MailInfoDTO;
import com.marvels.financial.loan.dto.McamLoanApplyContactInfo;
import com.marvels.financial.loan.dto.McamLoanApplyInfoDTO;
import com.marvels.financial.loan.dto.McfeCustomerRepaymentPlanDTO;
import com.marvels.financial.loan.dto.ProfessionalInformation;
import com.marvels.financial.loan.dto.ResidentialInformation;
import com.marvels.financial.loan.service.ShzxInterfaceSendJobApi;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;

@Service
public class ShzxInterfaceSendJobImpl implements ShzxInterfaceSendJobApi {

	private static String orgcode = "Q10155800HOQ00";// 机构名称
	
	@Value("${config.properties.path}")
	private String configPropertiesPath;
	
	@Autowired
	private FinancialConsumerExternalApi consumerExternalApi;
	
	@Autowired
	private FinancialConsumerApproveApi consumerApproveApi;
	
	@Autowired
	private McfeCustomerRepaymentPlanDao mcfeCustomerRepaymentPlanDao;
	
	@Autowired
	private ShzxUploadDataDao shzxUploadDataDao;
	
	@Autowired
	private ShzxService shzxService;
	
	@Autowired
	McamLoanApplyInfoCommonDao mcamLoanApplyInfoCommonDao;
	
	@Override
	public void shzxInterfaceSend()  throws Exception{
		MarvelsLogUtil.getInstance().info(">>>>>>>>>>>>>>>>>上海资信上传数据定时任务开始");
		String isShzxDataUpload = ServerProperties.getValue(configPropertiesPath, "common.properties", "is_shzx_data_upload");
		int shzxDataIntervalDays = Integer.parseInt(ServerProperties.getValue(configPropertiesPath, "common.properties", "shzx_data_interval_days"));
		if (!Boolean.parseBoolean(isShzxDataUpload)) {
			return;
		}
		MarvelsLogUtil.getInstance().info(">>>>>>>>>>>>>上海资信上传数据定时任务开始>>>>>>>>>>>>>");
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyyMMdd");
		int pageSize = Integer.parseInt(ServerProperties.getValue(configPropertiesPath, "common.properties", "shzx_page_size"));
		// 一次性发送三个月的数据
		
		for (int month = 0; month > -3; month--) {
			String lastDay = DateUtil.formatDate(DateUtil.date());
			String yearMonth = DateUtil.format(DateUtil.offsetMonth(DateUtil.date(), month), "yyyy-MM");
			if(month != 0){
				lastDay = DateUtil.formatDate(DateUtil.endOfMonth(DateUtil.offsetMonth(DateUtil.date(), month)));
			}
			int count=shzxUploadDataDao.paymentInfoListCount(shzxDataIntervalDays, yearMonth, lastDay);
			int totalPage = 0;
			if (count % pageSize == 0 && count != 0) {
				totalPage = count / pageSize;
			} else {
				totalPage = count / pageSize + 1;
			}
			for (int j = 1; j <= totalPage; j++) {
				ExcelInfo excelInfo = new ExcelInfo();
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(new Date());
				calendar.set(Calendar.DATE, (calendar.get(Calendar.DATE) + 1));
				int offset = (j - 1) * pageSize;
				int limit = pageSize;
				List<Map<String, Object>> listPaymentInfo = shzxUploadDataDao.paymentInfoList(
						shzxDataIntervalDays, yearMonth, lastDay, offset, limit);
				if (listPaymentInfo != null) {
					List<LoanBusinessInformation> loanBusinessInformationList = new ArrayList<LoanBusinessInformation>();
					List<IdentityInformation> identityInformationList = new ArrayList<IdentityInformation>();
					List<ProfessionalInformation> professionalInformationList = new ArrayList<ProfessionalInformation>();
					List<LoanApplicationInformation> loanApplicationInformationList = new ArrayList<LoanApplicationInformation>();
					List<ResidentialInformation> residentialInformationList = new ArrayList<ResidentialInformation>();
					for (Map<String, Object> mapPaymentInfo : listPaymentInfo) {
						try {
							String loanId = mapPaymentInfo.get("loan_id").toString();
							if(mapPaymentInfo.get("repaymented_time") != null){
								LoanBusinessInformation loanBusinessInformation = new LoanBusinessInformation();
								loanBusinessInformation.setP2pOrganizationCode(orgcode);
								loanBusinessInformation.setLoanType("99");
								/**
								 * 贷款合同号码
								 */
		
								/**
								 * 业务号
								 */
								loanBusinessInformation.setServiceNumber(
										mapPaymentInfo.get("loan_id") == null ? "" : mapPaymentInfo.get("loan_id").toString());
		
								/**
								 * 发生地点
								 */
								loanBusinessInformation.setPlaceOfOccurrence("440305");
								/**
								 * 开户日期
								 */
								loanBusinessInformation.setOpeningDate(mapPaymentInfo.get("loan_time") == null ? ""
										: simpleDateFormat2
												.format(simpleDateFormat.parse(mapPaymentInfo.get("loan_time").toString())));
		
								/**
								 * 到期日期
								 */
								loanBusinessInformation.setMaturityDate(mapPaymentInfo.get("max_repaymented_time") == null ? ""
										: simpleDateFormat2.format(
												simpleDateFormat.parse(mapPaymentInfo.get("max_repaymented_time").toString())));
		
								/**
								 * 币种
								 */
								loanBusinessInformation.setCurrency("CNY");
		
								/**
								 * 授信额度
								 */
								loanBusinessInformation.setCreditLine(new DecimalFormat("0")
										.format(Double.parseDouble(mapPaymentInfo.get("loan_money_act").toString())));
		
								/**
								 * 共享授信额度
								 */
								loanBusinessInformation.setSharedCreditLine("0");
		
								/**
								 * 最大负债额
								 */
								loanBusinessInformation.setMaximumLiabilities(mapPaymentInfo.get("max_overdue_money") == null
										? "0"
										: new DecimalFormat("0").format(
												Double.parseDouble(mapPaymentInfo.get("max_overdue_money").toString())));
		
								/**
								 * 担保方式
								 */
								loanBusinessInformation.setGuaranteeMode("9");
		
								/**
								 * 还款频率
								 */
								loanBusinessInformation.setRepaymentFrequency("01");
		
								/**
								 * 还款月数
								 */
								loanBusinessInformation.setMonthsOfRepayment(mapPaymentInfo.get("apply_terms") == null ? "0"
										: mapPaymentInfo.get("apply_terms").toString());
		
								/**
								 * 剩余还款月数
								 */
								loanBusinessInformation.setRemainingMonths(mapPaymentInfo.get("remain_repayment_terms") == null
										? "0" : mapPaymentInfo.get("remain_repayment_terms").toString());
		
								/**
								 * 协定还款期数
								 */
								loanBusinessInformation.setAgreedRepaymentPeriod(mapPaymentInfo.get("apply_terms") == null ? "0"
										: mapPaymentInfo.get("apply_terms").toString());
		
								/**
								 * 协定期还款额
								 */
								loanBusinessInformation.setAgreedAmount(mapPaymentInfo.get("repayment") == null ? "0"
										: new DecimalFormat("0")
												.format(Double.parseDouble(mapPaymentInfo.get("repayment").toString())));
		
								/**
								 * 结算/应还款日期
								 */
								loanBusinessInformation.setSettlementDueDate(mapPaymentInfo.get("repaymented_time") == null
										? simpleDateFormat2
												.format(simpleDateFormat.parse(mapPaymentInfo.get("loan_time").toString()))
										: simpleDateFormat2.format(
												simpleDateFormat.parse(mapPaymentInfo.get("repaymented_time").toString())));
		
								/**
								 * 最近一次实际还款日期
								 */
								loanBusinessInformation.setTheLastActualRepaymentDate(
										mapPaymentInfo.get("recent_real_repayment_time") == null ? ""
												: simpleDateFormat2.format(simpleDateFormat
														.parse(mapPaymentInfo.get("recent_real_repayment_time").toString())));
		
								/**
								 * 本月应还款金额
								 */
								loanBusinessInformation.setRepaymentAmountThisMonth(
										mapPaymentInfo.get("this_month_repayment_amount") == null ? "0"
												: new DecimalFormat("0").format(Double.parseDouble(
														mapPaymentInfo.get("this_month_repayment_amount").toString())));
		
								/**
								 * 本月实际还款金额
								 */
								loanBusinessInformation.setActualRepaymentAmountThisMonth(
										mapPaymentInfo.get("this_month_real_repayment_amount") == null ? "0"
												: new DecimalFormat("0").format(Double.parseDouble(
														mapPaymentInfo.get("this_month_real_repayment_amount").toString())));
		
								/**
								 * 余额
								 */
								loanBusinessInformation.setBalance(mapPaymentInfo.get("remain_principal") == null ? "0"
										: new DecimalFormat("0")
												.format(Double.parseDouble(mapPaymentInfo.get("remain_principal").toString())));
		
								/**
								 * 当前逾期期数
								 */
								loanBusinessInformation.setCurrentOverdue(mapPaymentInfo.get("overdue_terms") == null ? "0"
										: mapPaymentInfo.get("overdue_terms").toString());
		
								/**
								 * 当前逾期总额
								 */
								loanBusinessInformation.setCurrentTotalOverdue(mapPaymentInfo.get("overdue_money") == null ? "0"
										: new DecimalFormat("0")
												.format(Double.parseDouble(mapPaymentInfo.get("overdue_money").toString())));
		
								/**
								 * 逾期31-60天未归还贷款本金
								 */
								loanBusinessInformation
										.setOverdue31To60DaysPrincipal(mapPaymentInfo.get("31To61Nopay") == null ? "0"
												: new DecimalFormat("0").format(
														Double.parseDouble(mapPaymentInfo.get("31To61Nopay").toString())));
		
								/**
								 * 逾期61-90天未归还贷款本金
								 */
								loanBusinessInformation
										.setOverdue61To90DaysPrincipal(mapPaymentInfo.get("61To90Nopay") == null ? "0"
												: new DecimalFormat("0").format(
														Double.parseDouble(mapPaymentInfo.get("61To90Nopay").toString())));
		
								/**
								 * 逾期91-180天未归还贷款本金
								 */
								loanBusinessInformation
										.setOverdue91To180DaysPrincipal(mapPaymentInfo.get("91To181Nopay") == null ? "0"
												: new DecimalFormat("0").format(
														Double.parseDouble(mapPaymentInfo.get("91To181Nopay").toString())));
		
								/**
								 * 逾期180天以上未归还贷款本金
								 */
								loanBusinessInformation.setOverdue180DaysPrincipal(mapPaymentInfo.get("181Nopay") == null ? "0"
										: new DecimalFormat("0")
												.format(Double.parseDouble(mapPaymentInfo.get("181Nopay").toString())));
		
								/**
								 * 累计逾期期数
								 */
								loanBusinessInformation.setCumulativeOverdue(mapPaymentInfo.get("overdue_terms") == null ? "0"
										: mapPaymentInfo.get("overdue_terms").toString());
		
								/**
								 * 最高逾期期数
								 */
								loanBusinessInformation.setMaximumOverdue(mapPaymentInfo.get("overdue_terms") == null ? "0"
										: mapPaymentInfo.get("overdue_terms").toString());
		
								/**
								 * 五级分类状态
								 */
								loanBusinessInformation.setFiveLevelClassification("9");
		
								/**
								 * 账户状态
								 */
								loanBusinessInformation.setAccountStatus(mapPaymentInfo.get("consum_status").toString());
		
								List<McfeCustomerRepaymentPlanDTO> pymtPlanList=mcfeCustomerRepaymentPlanDao.selectLessTodayPlan(loanId);
								StringBuilder paymentStatus = new StringBuilder();
								for (int i = 1; i <= 24; i++) {
									if (i < 24 - pymtPlanList.size() && (24 - pymtPlanList.size()) > 0) {
										paymentStatus.append("/");
										continue;
									} else if (i == (24 - pymtPlanList.size())) {
										paymentStatus.append("/");
									}
								}
								int k = 1;
								for (McfeCustomerRepaymentPlanDTO mpPaymentPlanInfo : pymtPlanList) {
									if (k == pymtPlanList.size()
											&& "3".equals(mapPaymentInfo.get("consum_status").toString())) {
										paymentStatus.append("C");
									} else if (mpPaymentPlanInfo.getStatus() != 1) {// 不是逾期且不是提前还款
										paymentStatus.append("N");
									} else {
										int days = differentDaysByMillisecond(mpPaymentPlanInfo.getPaymentDate(), new Date());
										if (days <= 30 && days >= 1) {
											paymentStatus.append("1");
										} else if (days <= 60 && days >= 31) {
											paymentStatus.append("2");
										} else if (days <= 90 && days >= 61) {
											paymentStatus.append("3");
										} else if (days <= 120 && days >= 91) {
											paymentStatus.append("4");
										} else if (days <= 150 && days >= 121) {
											paymentStatus.append("5");
										} else if (days <= 180 && days >= 151) {
											paymentStatus.append("6");
										} else {
											paymentStatus.append("7");
										}
									}
									k++;
								}
								/**
								 * 24月（账户）还款状态
								 */
								loanBusinessInformation.setRepaymentStatus(paymentStatus.toString());
		
								/**
								 * 账户拥有者信息提示
								 */
								loanBusinessInformation.setAccountOwnerInformation("2");
		
								/**
								 * 姓名
								 */
								loanBusinessInformation.setName(mapPaymentInfo.get("cust_name") == null ? ""
										: mapPaymentInfo.get("cust_name").toString());
		
								/**
								 * 证件类型
								 */
								loanBusinessInformation.setDocumentType("0");
		
								/**
								 * 证件号码
								 */
								loanBusinessInformation.setIdentificationNumber(mapPaymentInfo.get("cust_id_card") == null ? ""
										: mapPaymentInfo.get("cust_id_card").toString());
								loanBusinessInformationList.add(loanBusinessInformation);
							}
							McamLoanApplyInfoDTO mcamLoanApplyInfoDTO=new McamLoanApplyInfoDTO();
							mcamLoanApplyInfoDTO.setLoanId(loanId);
							Map<String, Object> map = consumerApproveApi.selectShzxNeedLoanApplyInfo(mcamLoanApplyInfoDTO);
							// 身份信息
	//						if (list != null && list.size() > 0) {
	//							for (Map<String, Object> map : list) {
									try {
										if(map!=null){
											String name = map.get("cust_name") == null ? "" : map.get("cust_name").toString();
											String custIdCard = map.get("cust_id_card") == null ? ""
													: map.get("cust_id_card").toString();
											String mobile = map.get("mobile_num") == null ? ""
													: map.get("mobile_num").toString();
											IdentityInformation identityInformation = new IdentityInformation();
											/**
											 * P2P机构代码
											 */
											identityInformation.setP2pOrganizationCode(orgcode);
											/**
											 * 姓名
											 */
											identityInformation.setName(name);
	
											/**
											 * 证件类型
											 */
											identityInformation.setDocumentType("0");
	
											/**
											 * 证件号码
											 */
											identityInformation.setIdentificationNumber(custIdCard);
	
											/**
											 * 性别
											 */
											identityInformation
													.setGender(map.get("sex") == null ? "9" : map.get("sex").toString());
	
											/**
											 * 出生日期
											 */
											identityInformation.setDateOfBirth(map.get("birth_date") == null ? "19010101"
													: simpleDateFormat2
															.format(simpleDateFormat.parse(map.get("birth_date").toString())));
	
											/**
											 * 婚姻状况
											 */
											identityInformation.setMaritalStatus(map.get("marriage_name") == null ? "90"
													: map.get("marriage_name").toString());
	
											/**
											 * 最高学位
											 */
											identityInformation.setHighestDegree(map.get("education_composition") == null ? "9"
													: map.get("education_composition").toString());
	
											/**
											 * 最高学历
											 */
											identityInformation.setHighestEducation(map.get("education_level") == null ? "99"
													: map.get("education_level").toString());
	
											/**
											 * 住宅电话
											 */
											identityInformation.setHomePhone(
													map.get("mobile_num") == null ? "" : map.get("mobile_num").toString());
	
											/**
											 * 手机号码
											 */
											identityInformation.setPhoneNumber(mobile);
	
											/**
											 * 单位电话
											 */
											identityInformation.setWorkTelephone(
													map.get("office_phone") == null ? "" : map.get("office_phone").toString());
	
											/**
											 * 通讯地址
											 */
											String address = "-";
											if (map.get("address") != null
													&& StringUtils.isNotEmpty(map.get("address").toString())) {
												if (map.get("address").toString().length() >= 30) {
													address = map.get("address").toString().substring(0, 30);
												} else {
													address = map.get("address").toString();
												}
											}
											identityInformation.setPostalAddress(address);
	
											/**
											 * 通讯地址邮政编码
											 */
											identityInformation.setPostalCode("999999");
	
											String id_card_address = "";
											/**
											 * 户籍地址
											 */
											if (map.get("id_card_address") != null
													&& StringUtils.isNotEmpty(map.get("id_card_address").toString())) {
												if (map.get("id_card_address").toString().length() >= 30) {
													id_card_address = map.get("id_card_address").toString().substring(0, 30);
												} else {
													id_card_address = map.get("id_card_address").toString();
												}
											}
											identityInformation.setPermanentAddress(id_card_address);
	
											/**
											 * 配偶姓名
											 */
											identityInformation.setSpouseName(
													map.get("mate_name") == null ? "" : map.get("mate_name").toString());
	
											/**
											 * 配偶联系电话
											 */
											identityInformation.setSpousePhone(
													map.get("mate_mobile") == null ? "" : map.get("mate_mobile").toString());
											McamLoanApplyContactInfo info=new McamLoanApplyContactInfo();
											info.setLoanId(map.get("loan_id").toString());
											
											String userId = mcamLoanApplyInfoCommonDao.selectApplyInfoByLoanId(loanId);
											MarvelsLogUtil.getInstance().info("上海资信上传数据组装，userid：" + userId + "，loanId:" + loanId);
											List<Map<String, Object>> linkManList = shzxUploadDataDao.linkManList(userId, loanId);
											if(linkManList != null && linkManList.size() > 0){
												identityInformation.setFirstContactName(linkManList.get(0).get("linkmanName") == null ? "-" : linkManList.get(0).get("linkmanName").toString());
												identityInformation.setFirstContactRelationship("8");
												identityInformation.setFirstContactPersonPhone(linkManList.get(0).get("linkmanMobileNum") == null ? " " : linkManList.get(0).get("linkmanMobileNum").toString());
											}else{
												identityInformation.setFirstContactName(" ");
												identityInformation.setFirstContactRelationship(" ");
												identityInformation.setFirstContactPersonPhone(" ");
											}
											/*List<McamLoanApplyContactInfo> linkMansList=consumerApproveApi.selectContactByLoanId(info);
											if (linkMansList != null && linkMansList.size() > 0) {
												*//**
												 * 第一联系人姓名
												 *//*
												identityInformation.setFirstContactName(linkMansList.get(0).getContactName() == null ? " " : linkMansList.get(0).getContactName());
	
												*//**
												 * 第一联系人关系
												 *//*
												if ("1".equals(linkMansList.get(0).getRelationCode()))// 朋友
												{
													identityInformation.setFirstContactRelationship("6");
												} else if ("2".equals(linkMansList.get(0).getRelationCode())) {// 同事
													identityInformation.setFirstContactRelationship("5");
												} else {
													identityInformation.setFirstContactRelationship("8");
												}
												*//**
												 * 第一关系人联系电话
												 *//*
												identityInformation
														.setFirstContactPersonPhone(linkMansList.get(0).getContactMobile() == null ? " " : linkMansList.get(0).getContactMobile());
	
												if (linkMansList.size() > 1) {
													*//**
													 * 第二联系人姓名
													 *//*
													identityInformation
															.setSecondContactName(linkMansList.get(1).getContactName());
	
													*//**
													 * 第二联系人关系
													 *//*
													if ("1".equals(linkMansList.get(0).getRelationCode()))// 朋友
													{
														identityInformation.setSecondContactRelationship("6");
													} else if ("2".equals(linkMansList.get(0).getRelationCode())) {// 同事
														identityInformation.setSecondContactRelationship("5");
													} else {// 同学,其他
														identityInformation.setSecondContactRelationship("8");
													}
	
													*//**
													 * 第二关系人联系电话
													 *//*
													identityInformation.setSecondContactPersonPhone(
															linkMansList.get(1).getContactMobile());
												}
											}*/
	
											// 职业信息
											ProfessionalInformation professionalInformation = new ProfessionalInformation();
											professionalInformation.setP2pOrganizationCode(orgcode);
											/**
											 * 姓名
											 */
											professionalInformation.setName(name);
	
											/**
											 * 证件类型
											 */
											professionalInformation.setDocumentType("0");
	
											/**
											 * 证件号码
											 */
											professionalInformation.setIdentificationNumber(custIdCard);
	
											/**
											 * 职业
											 */
											professionalInformation.setOccupation("Z");
	
											/**
											 * 单位名称
											 */
											professionalInformation.setUnitName((map.get("company_name") == null
													|| StringUtils.isBlank(map.get("company_name").toString())) ? "暂缺"
															: map.get("company_name").toString());
	
											/**
											 * 单位所属行业
											 */
											professionalInformation.setUnitOwnedIndustry("Z");
	
											/**
											 * 单位地址
											 */
											professionalInformation.setUnitAddress(map.get("company_address") == null ? ""
													: map.get("company_address").toString());
	
											/**
											 * 单位地址邮政编码
											 */
											professionalInformation.setUnitAddressZipCode("999999");
	
											/**
											 * 职务
											 */
											professionalInformation.setPost("9");
	
											/**
											 * 职称
											 */
											professionalInformation.setTitle("9");
	
											/**
											 * 年收入
											 */
	
											if (map.get("monthly_income") != null
													&& StringUtils.isNotEmpty(map.get("monthly_income").toString())) {
												if (map.get("monthly_income").toString().contains("-")) {
													if (map.get("monthly_income").toString().split("-")[0].contains("元")) {
														professionalInformation
																.setAnnualIncome(
																		String.valueOf(new DecimalFormat("0").format(Double
																				.parseDouble(map.get("monthly_income")
																						.toString().split("-")[0].split("元")[0])
																				* 12)));
													} else {
														professionalInformation
																.setAnnualIncome(
																		String.valueOf(
																				new DecimalFormat("0").format(Double
																						.parseDouble(map.get("monthly_income")
																								.toString().split("-")[0])
																						* 12)));
													}
	
												} else if (map.get("monthly_income").toString().contains("以上")) {
													if (map.get("monthly_income").toString().contains("元以上")) {
														professionalInformation
																.setAnnualIncome(
																		String.valueOf(
																				new DecimalFormat("0").format(Double
																						.parseDouble(map.get("monthly_income")
																								.toString().split("元以上")[0])
																						* 12)));
													} else {
														professionalInformation
																.setAnnualIncome(
																		String.valueOf(
																				new DecimalFormat("0").format(Double
																						.parseDouble(map.get("monthly_income")
																								.toString().split("以上")[0])
																						* 12)));
													}
	
												} else if (map.get("monthly_income").toString().contains("以内")) {
													professionalInformation.setAnnualIncome(
															String.valueOf(new DecimalFormat("0").format(Double.parseDouble(
																	map.get("monthly_income").toString().split("以内")[0])
																	* 12)));
												} else {
													professionalInformation.setAnnualIncome(
															String.valueOf(new DecimalFormat("0").format(Double.parseDouble(
																	map.get("monthly_income").toString().split("元")[0]) * 12)));
												}
	
											}
	
											ResidentialInformation residentialInformation = new ResidentialInformation();
											residentialInformation.setDocumentType("0");
											residentialInformation.setIdentificationNumber(custIdCard);
											residentialInformation.setLivingCondition("9");
											residentialInformation.setName(name);
											residentialInformation.setP2pOrganizationCode(orgcode);
											residentialInformation.setResidentialAddress(address);
											residentialInformation.setResidentialAddressPostalCode("999999");
	
											LoanApplicationInformation loanApplicationInformation = new LoanApplicationInformation();
											loanApplicationInformation.setDocumentType("0");
											loanApplicationInformation.setP2pOrganizationCode(orgcode);
											loanApplicationInformation.setIdentificationNumber(custIdCard);
											loanApplicationInformation.setLoanApplicationNumber((map.get("loan_id") == null
													|| StringUtils.isEmpty(map.get("loan_id").toString())) ? ""
															: map.get("loan_id").toString());
											loanApplicationInformation.setName(name);
											loanApplicationInformation
													.setLoanApplicationAmount(map.get("apply_money") == null ? "0"
															: new DecimalFormat("0").format(
																	Double.parseDouble(map.get("apply_money").toString())));
											loanApplicationInformation.setTypeOfLoanApplication("91");// 贷款申请类型
											loanApplicationInformation.setMonthsOfLoanApplications(
													map.get("apply_terms") == null ? "0" : map.get("apply_terms").toString());
											loanApplicationInformation.setLoanApplicationTime((map.get("apply_time") == null
													|| StringUtils.isBlank(map.get("apply_time").toString())) ? ""
															: simpleDateFormat2.format(
																	simpleDateFormat.parse(map.get("apply_time").toString())));
											loanApplicationInformation.setLoanApplicationStatus(
													map.get("status") == null ? "" : map.get("status").toString());
	
											identityInformationList.add(identityInformation);
											professionalInformationList.add(professionalInformation);
											residentialInformationList.add(residentialInformation);
											loanApplicationInformationList.add(loanApplicationInformation);
										}
									} catch (Exception e) {
										e.printStackTrace();
										StringWriter sw = new StringWriter();
										e.printStackTrace(new PrintWriter(sw));
										MarvelsLogUtil.getInstance().info("===========上海资信上传数据异常" + e.getMessage());
										MailInfoDTO mail = new MailInfoDTO();
										mail.setFromAddress("marvel_core@creditseconds.com");
										mail.setContent("上海资信上传数据异常:" + e.getMessage() + ",详细异常:" + sw);
										mail.setSubject("上海资信上传数据");
										mail.setToEmails("tangpw@creditseconds.com");
										consumerExternalApi.sendMailSingle(mail);
										continue;
									}
	//							}
	//
	//						}
	
						} catch (Exception e) {
							e.printStackTrace();
							StringWriter sw = new StringWriter();
							e.printStackTrace(new PrintWriter(sw));
							MarvelsLogUtil.getInstance().info("===========上海资信上传数据异常" + e.getMessage());
							MailInfoDTO mail = new MailInfoDTO();
							mail.setFromAddress("marvel_core@cloudtechcredit.com");
							mail.setContent("上海资信上传数据异常:" + e.getMessage() + ",详细异常:" + sw);
							mail.setSubject("上海资信上传数据");
							mail.setToEmails("tangpw@cloudtechcredit.com");
							consumerExternalApi.sendMailSingle(mail);
							continue;
						}
					}
					excelInfo.setIdentityInformation(identityInformationList);
					excelInfo.setProfessionalInformation(professionalInformationList);
					excelInfo.setResidentialInformation(residentialInformationList);
					excelInfo.setLoanApplicationInformation(loanApplicationInformationList);
					excelInfo.setLoanBusinessInformation(loanBusinessInformationList);
				}
				MarvelsLogUtil.getInstance().info("===============上海资信上传贷款数据开始上传==============");
	
				if (excelInfo != null) {
					try {
						MarvelsLogUtil.getInstance().info("===============上海资信上传贷款数据==============" + JSONObject.toJSONString(excelInfo));
						com.fintech.third.model.shzx.ExcelInfo param = JSON.parseObject(JSONObject.toJSONString(excelInfo),
								com.fintech.third.model.shzx.ExcelInfo.class);
						shzxService.messageUpload(param);
					} catch (Exception e) {
						MarvelsLogUtil.getInstance().error("===============上海资信上传贷款数据开始异常==============", e);
						continue;
					}
				}
				MarvelsLogUtil.getInstance().info("===============上海资信上传贷款数据定时任务结束==============");
			}
		}

	}

	/**
	 * 获取两个日期相差的月数
	 * 
	 * @param d1
	 *            较大的日期
	 * @param d2
	 *            较小的日期
	 * @return 如果d1>d2返回 月数差 否则返回0
	 */
	public static int getMonthDiff(Date d1, Date d2) {
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();
		c1.setTime(d1);
		c2.setTime(d2);
		if (c1.getTimeInMillis() < c2.getTimeInMillis())
			return 0;
		int year1 = c1.get(Calendar.YEAR);
		int year2 = c2.get(Calendar.YEAR);
		int month1 = c1.get(Calendar.MONTH);
		int month2 = c2.get(Calendar.MONTH);
		int day1 = c1.get(Calendar.DAY_OF_MONTH);
		int day2 = c2.get(Calendar.DAY_OF_MONTH);
		// 获取年的差值 假设 d1 = 2015-8-16 d2 = 2011-9-30
		int yearInterval = year1 - year2;
		// 如果 d1的 月-日 小于 d2的 月-日 那么 yearInterval-- 这样就得到了相差的年数
		if (month1 < month2 || month1 == month2 && day1 < day2)
			yearInterval--;
		// 获取月数差值
		int monthInterval = (month1 + 12) - month2;
		if (day1 < day2)
			monthInterval--;
		monthInterval %= 12;
		return yearInterval * 12 + monthInterval;
	}

	public static int differentDaysByMillisecond(Date date1, Date date2) {
		int days = (int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24));
		return days;
	}

}
